import logging
import sys
import os
from datetime import datetime
from ..config import settings

# 获取今天的日期
today = datetime.now().strftime("%Y%m%d")

# 确保日志目录存在
os.makedirs(settings.log_dir, exist_ok=True)

# 配置根日志记录器
logging.basicConfig(
    level=getattr(logging, settings.log_level),
    format=settings.log_format,
    handlers=[
        logging.FileHandler(
            os.path.join(settings.log_dir, f"cardsys_{today}.log"),
            encoding='utf-8'
        ),
        logging.StreamHandler(sys.stdout)
    ]
)

def get_logger(name: str) -> logging.Logger:
    """
    获取指定名称的日志记录器
    :param name: 日志记录器名称
    :return: Logger对象
    """
    logger = logging.getLogger(name)
    logger.setLevel(getattr(logging, settings.log_level))
    return logger

def log_transaction(trans_type: str, direction: str, message: str, **kwargs):
    """
    记录交易日志
    :param trans_type: 交易类型（CEQ/CEP等）
    :param direction: 日志方向（REQUEST/RESPONSE/ERROR/INFO）
    :param message: 日志消息
    :param kwargs: 额外的日志字段
    """
    logger = get_logger(trans_type)
    
    # 构建日志消息
    log_message = f"{message}"
    if kwargs:
        log_message += " | " + " | ".join(f"{k}={v}" for k, v in kwargs.items())
    
    # 根据方向记录日志
    if direction == "ERROR":
        logger.error(log_message)
    else:
        logger.info(f"{direction} | {log_message}") 